package com.linkhouse.interfaces;

import com.baidu.aip.face.AipFace;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.linkhouse.domain.po.User;
import com.linkhouse.mapper.UserMapper;
import com.linkhouse.util.ImageUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 该类用于处理用户面部信息，用于卖房、租房前房主信息的认证
 * 1. 用户注册时不强制要求录入面部信息(否则可能导致新用户的流失)
 * 2. 用户注册后也可自愿完善个人资料，比如面部信息
 * 3. 只有当用户要进行卖房或出租房时，如果没有录入面部信息才会强制要求录入面部信息
 *
 * @author J-B-Y
 * @description
 * @date 2022/5/29-14:28
 */
@RequestMapping("faceinfo")
@Controller
@EnableDiscoveryClient
public class FaceController {

    private static final String APP_ID = "26339985";
    private static final String API_KEY = "ktewiF5neGzeqCt2WIoxaNhR";
    private static final String SECRET_KEY = "CA4qCakon7RD9EFjleIa4I8YYnxREWxN";

    @Autowired
    private UserMapper userMapper;



    /**
     * 前端采集人像信息
     */
    @RequestMapping("toFaceInfo")
    public String toFaceInfo() {
        System.out.println("进入方法");
        return "FaceRegister";
    }
    /**
     * 跳转人脸登录
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "FaceLogin";
    }



    /**
     * 存储(数据库)并上传(百度云)人像信息
     * 1. 将人像上传到项目文件夹
     * 2. 将人像存储路径存入DB
     * 2. 上传用户人像信息到百度云
     */
    @PostMapping("collectFaceInfo")
    @ResponseBody
    public String collectFaceInfo(String username, String faceBase, HttpServletRequest request) {

        // 根据用户名判断数据库中有没有该用户
        List<User> list = userMapper.selectList(new QueryWrapper<User>()
                .eq("username", username)
        );
        if(list.size() == 0){
            return "用户不存在";
        }

        // 1. 将人像存到本地文件夹
        // 人像上传路径
        String upPath = "E:\\workspace_idea\\project_linkhouse\\photo";
        // 图片名称
        String fileName = username + System.currentTimeMillis() + ".png";
        System.out.println(upPath + "\\" + fileName);
        File file = new File(upPath + "\\" + fileName);
        // 将base64转图片存入本地文件夹中
        ImageUtil.uploadImage(faceBase, file);

        // 2. 将人像图片路径存入DB
        User user = new User();
        user.setFaceId(upPath + fileName);
        userMapper.update(user, new QueryWrapper<User>()
                .eq("username", username)
        );


        // 3. 将人像上传到百度云
        AipFace aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", list.get(0).getUsername());   // 用户信息
        options.put("quality_control", "NORMAL");  // 人像质量级别
        options.put("liveness_control", "LOW");    // 活体检测级别
        options.put("action_type", "REPLACE");      // 重复注册时追加到用户原先的人像库

        String image = faceBase;      // 取决于image_type参数，传入BASE64字符串或URL字符串或FACE_TOKEN字符串
        String imageType = "BASE64";  // 上传图像格式
        String groupId = "group1";    // 用户组id
        String userId = String.valueOf(list.get(0).getId());      // 用户id

        // 人脸注册(更新)
        JSONObject res = aipFace.updateUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));

        return "success";

    }


    /**
     * 人脸登录
     * @return
     */
    @PostMapping("faceLogin")
    @ResponseBody
    public String faceLogin(String username, String faceBase){
        AipFace aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<>();

        JSONObject res = aipFace.search(faceBase, "BASE64", "group1", options);

//        System.out.println(res.toString(2));
//        System.out.println(res.getJSONObject("result"));
//        System.out.println(res.getJSONObject("result").getJSONArray("user_list"));
        JSONObject user = (JSONObject) res.getJSONObject("result").getJSONArray("user_list").get(0);
        Double score = (Double) user.get("score");
        System.out.println(score);
        if(score >= 80){
            return "success";
        }
        return "fail";
    }
}